<!--我们的登录界面-->
<template>
  <div class="backgroud" v-loading="loading"  element-loading-text="系统登录验证中，请稍后">
    <div class="login">
      <!--登录表单-->
      <el-form style="width: 100% ;height: 100%" :model="user" :rules="rules" ref="loginRef">
        <div style="margin-top: 72px; margin-left: 50px;font-size:27px;font-weight: bolder">
          欢迎登录-简捷报
        </div>
        <div style="display: flex;align-items: center; justify-content: center; margin-top: 37px">
          <el-tabs v-model="activeName" stretch='true' style="width: 80%;">

            <el-tab-pane label="账号登录" name="accountLogin">
              <!--           账号登录的内容 -->

              <el-form-item style="margin-top: 42px" prop="name">
                <!--                账号输入框-->
                <el-input placeholder="请输入用户名" v-model="user.name" size="120px" prefix-icon="el-icon-user"></el-input>
              </el-form-item>

              <el-form-item style="margin-top: 27px" prop="password">
                <!--                密码输入框-->
                <el-input placeholder="请输入密码" size="120px" v-model="user.password" show-password
                          prefix-icon="el-icon-lock"></el-input>
              </el-form-item>

              <el-form-item style="margin-top: 27px" prop="code">
                <!--                验证码-->
                <div style="display: flex">
                  <el-input style="flex: 1" prefix-icon="el-icon-circle-check" v-model="user.code"></el-input>

                  <div style="flex: 1;margin-left: 27px;width: 37px; height: 37px">
                    <valid-code @update:value="getCode"/>
                  </div>

                </div>
              </el-form-item>

              <el-form-item style="margin-top: 27px">
                <!--                登录按钮-->
                <el-button type="primary" style="width: 100%;height: 42px;font-size: 16px;" @click="login">
                  登&nbsp&nbsp&nbsp&nbsp&nbsp录
                </el-button>
              </el-form-item>

              <div style="display: flex">
                <div style="flex: 1">还没有账号吗？ <el-link href="http://localhost:39052/register" target="_blank" type="primary" :underline="false">去注册</el-link></div>
                <div style="flex: 1;text-align: right"><span style="color: dodgerblue">向kinroy求助</span></div>
              </div>

            </el-tab-pane>
            <el-tab-pane label="手机登录" name="phoneLogin">

              <el-form :model="user" :rules="rules_phone" ref="loginPhoneRef">
                <!--            手机登录的内容-->
                <el-form-item style="margin-top: 42px" prop="phone">
                  <!--                手机号输入框-->
                  <el-input placeholder="请输入手机号" v-model="user.phone" size="120px" prefix-icon="el-icon-phone"></el-input>
                </el-form-item>

                <el-form-item style="margin-top: 27px" prop="code">
                  <!--                验证码-->
                  <div style="display: flex">
                    <el-input style="flex: 1" prefix-icon="el-icon-circle-check" v-model="user.code" placeholder="请输入手机验证码"></el-input>
                    <div style="flex: 1;margin-left: 27px;width: 37px; height: 37px">
                      <el-button @click="sendCode" :disabled="disabled1">{{buttonText()}}</el-button>
                    </div>

                  </div>
                </el-form-item>

                <el-form-item style="margin-top: 27px">
                  <!--                登录按钮-->
                  <el-button type="primary" style="width: 100%;height: 42px;font-size: 16px;" @click="login" :disabled="disabled">
                    登&nbsp&nbsp&nbsp&nbsp&nbsp录
                  </el-button>

                </el-form-item>

                <div style="display: flex">
                  <div style="flex: 1">还没有账号吗？<el-link href="http://localhost:39052/register" target="_blank" type="primary" :underline="false">去注册</el-link></div>
                  <div style="flex: 1;text-align: right"><span style="color: dodgerblue">向kinroy求助</span></div>
                </div>

              </el-form>

            </el-tab-pane>

          </el-tabs>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import ValidCode from "@/components/ValidCode";
import axios from "axios";

export default {
  name: "Login",
  components: {
    ValidCode
  },
  data() {
    var validateCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else if (value.toLowerCase() != this.validCode) {
        callback(new Error("验证码错误"))
      } else {
        callback();
      }
    }

    var validPhone= (rule,value,callback)=>{
      //校验中国电话号码的正则表达式
      const chinesePhoneNumberRegex = /^1[3456789]\d{9}$/;
      if (value===''){
        this.disabled=true
        callback(new Error('请输入手机号'))
      }else if (!chinesePhoneNumberRegex.test(value)){
        this.disabled=true
        callback(new Error('请输入正确的手机号！'))
      }else {
        this.disabled=false
        callback();
      }
    }

    return {
      activeName: 'accountLogin',
      user: {
        name: '', //用户名
        password: '', //密码
        phone: '', //电话
        loginType: '', //登录方式
        code: ''//电话验证码或者账号登录时用户输入的验证码
      },
      validCode: '',
      //账号登录前端表单校验
      rules: {
        name: [
          {required: true, message: '请输入账号', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ],
        code: [
          {validator: validateCode, trigger: 'blur'}
        ]
      },
      //手机号验证码登录的前端表单校验
      rules_phone:{
        phone:[
          {validator: validPhone, trigger: 'blur'}
        ]
      },
    //  按下登录后进入loading状态
      loading:false,

    //  不符合登录条件则禁用
      disabled: false,


      isCounting: false,
      countdown:0,
      disabled1:false

    }
  },

  methods: {
    getCode(code) {
      //打印验证码
      console.log(code)
      this.validCode = code.toLowerCase();
    },
    login() {
      //  用户登录
      console.log(this.validCode);
      if (this.activeName == "accountLogin") {
        this.user.loginType = 0;//表示登录方式,默认密码登录
      } else {
        this.user.loginType = 1;//手机号登录
      }
      //前端的表单校验
      this.$refs["loginRef"].validate((valid) => {
        //表单验证通过且验证码正确才发送登录请求给后端
        if (valid) {
          this.loading = true
          //验证通过，才发送请求
          this.$request.post('/login/userlogin', this.user).then(res => {
            //todo: 重构一下返回值
            if (res.successFlag) {
              //登录成功，跳转页面
              this.$router.push('/Workbench')
              this.$message.success('登录成功！')
              //下面的localStorage 类似浏览器的缓存，可以用来存我们的用户数据，然后在其他页面也能获取
              //我们存的是一种键值对，所以用户信息为value我们要把user对象转换成json字符串
              localStorage.setItem("loginUser",JSON.stringify(res.data))
            } else {
              this.loading = false
              this.$message.error('登录失败！账号或密码错误！')
            }
          })
        }
      })
      if (this.user.loginType === 1) {
        this.loading = true
        //验证通过，才发送请求
        this.$request.post('/login/userlogin', this.user).then(res => {
          //todo: 重构一下返回值
          if (res.successFlag) {
            //登录成功，跳转页面
            localStorage.setItem("loginUser",JSON.stringify(res.data))
            this.$router.push('/')
            this.$message.success('登录成功！')
          } else {
            this.loading = false
            this.$message.error('验证码错误或已过期')
          }
        })

      }
    },
    sendCode() {
      //验证码按钮样式变化
      if (this.isCounting){
        return;
      }

      this.isCounting=true;
      this.countdown=60;
      const  times= setInterval(()=>{
        this.countdown--;
        if (this.countdown===0){
          clearInterval(times);
          this.isCounting=false;
          this.disabled1=false
        }
      },1000)
      //  手机验证发送手机验证码
      this.disabled1=true
      this.$request.get('/login/sendcode', {params:{
        phone :this.user.phone
        }}).then(res => {


            this.$notify({
              title: '验证码：',
              message: res,
              type: 'success'
            })

      })


      /*axios.get('http://localhost:39051/login/sendcode', this.user.phone).then(res => {
        this.$notify({
          title: '验证码：',
          message: res,
          type: 'success'
        })
      })*/
    },
    buttonText() {
      return this.isCounting ? `${this.countdown}秒后重新获取` : "获取验证码";
    },

  }
}
</script>

<style scoped>
/*设置一下背景的样式*/
.backgroud {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: right;
  background-image: url('../assets/login_bg.png');
  background-size: 100% 100%;
}

.login {
  display: flex;
  background-color: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  height: 600px;
  width: 500px;
  margin-right: 270px;
  border-radius: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)

}
</style>